//
//  PQResultSet.m
//  ObjectivePQ
//
//  Created by Ian Michell on 01/07/2007.
//  Copyright 2007 Ian Michell. All rights reserved.
//

#import "PQResultSet.h"


@implementation PQResultSet
- (void) print
{
	PQprintOpt options = {0};
	options.header = 1;
	options.align = 1;
	options.fieldSep = "|";
	PQprint(stdout, self->res, &options);
}

- (bool) next
{
	int rows = [self rowCount];
	self->currentRow++;
	if (currentRow < rows)
		return TRUE;
	
	return FALSE;
}

- (bool) previous
{
	/* If this was the first time we ran this, then return set the currentRow to the full row count */
	if (self->currentRow == -1)
		self->currentRow = [self rowCount];
	
	self->currentRow--;
	
	if (self->currentRow >= 0)
		return TRUE;
	
	return FALSE;
}

- (id) getByName: (NSString*) col
{
	int colNumber = PQfnumber(self->res, [col cString]);
	if (colNumber == -1)
		@throw [NSException exceptionWithName: @"NoSuchColumnException" reason: @"Column does not exist in resultset"
					     userInfo: nil];
	return [self get: colNumber];
}

- (id) get: (int) index
{
	if (index >= [self columnCount])
		@throw [NSException exceptionWithName: @"IndexOutOfRangeException" reason: @"Index value greater that column count"
			userInfo: nil];
	// FIXME Make this return a proper type (although as id)
	NSString* value = [[NSString alloc] initWithCString: PQgetvalue(self->res, currentRow, index)];
	return value;
}

- (NSString*) getColumnName: (int) index
{
	return [[NSString alloc] initWithCString: PQfname(self->res, index)];
}

/* Returns the number of rows */
- (int) rowCount
{
	return PQntuples(self->res);
}

- (int) columnCount
{
	return PQnfields(self->res);
}

- (void) close
{
	PQclear(self->res);
}
@end
